package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.OrderService;
import com.itheima.utils.JuHeSMSUtils;
import com.itheima.vo.OrderInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    @RequestMapping("/getToken")
    public Result getToken(){
        String token = UUID.randomUUID().toString();
        jedisPool.getResource().set(token, token);
        return Result.success("",token);
    }

    @RequestMapping("/submit")
    public Result submit(@RequestBody OrderInfoVo orderInfoVo){
        //页面中的token
        String token = orderInfoVo.getToken();

        if (StringUtils.isEmpty(token)){
            return Result.error("非法访问");
        }

        //redis中的token
        String redisToken = jedisPool.getResource().get(token);
        if (StringUtils.isEmpty(redisToken)){
            return Result.error("非法访问");
        }else {
            jedisPool.getResource().del(token);
        }


        //1.校验验证码
        String telephone = orderInfoVo.getTelephone();
        String validateCode = orderInfoVo.getValidateCode();
        String redisCode = jedisPool.getResource().get(RedisMessageConstant.SENDTYPE_ORDER + orderInfoVo.getTelephone());
        if (StringUtils.isEmpty(redisCode)){
            jedisPool.getResource().set(token,token);
            return Result.error("此手机号未发送验证码");
        }
        if (StringUtils.isEmpty(validateCode)||!redisCode.equals(validateCode)){
            jedisPool.getResource().set(token,token);
            return Result.error("验证码错误！");
        }

        //2.调用预约服务
       Result result= orderService.submit(orderInfoVo);
        if (result.isFlag()){
            //发送预约成功短信
            //JuHeSMSUtils.sendMessage(telephone);
        }else {
            jedisPool.getResource().set(token,token);
        }

        //3.返回结果
        return result;
    }
    @RequestMapping("/findById")
    public Result findById(Integer id){
        Map map=orderService.findById(id);
        return Result.success(MessageConstant.QUERY_ORDER_SUCCESS,map);
    }

}
